<?php
	class newsControl extends commonControl{
		/**
		 * 显示文章 用在全部文章 和未审核的文章
		 */
		public function index(){
			$catid = isset($_GET['catid']) ? $_GET['catid'] : false;//栏目id
			if($catid === false){
				$this->error('参数错误(查看栏目下文章需要栏目id)','',3);
			}
			$mid = isset($_GET['mid']) ? $_GET['mid'] : false; //模型id
			if($mid === false){
				$this->error('参数错误(查看栏目下文章需要模型id)','',3);
			}
			$tables = $this->getAllTableName($mid);
			$ptable = $tables['p']; //主表名  不带前缀
			$stable = $tables['s']; //附表名  不带前缀
			$pfixtable = $tables['pfix']; //主表 有前缀
			$sfixtable = $tables['sfix']; //附表 有前缀
			$news  = V($ptable);
			$news->view = array(
					"category" => array(
							"join_type" => "inner",
							"on" => $ptable.".catid = category.catid"
					),
					"user" => array(
							"join_type" => "inner",
							"on" => $ptable.".uid = user.uid"
					),
				);
			$art_num = C('ART_NUM'); //文章列表每页显示的条数
			$where_catid = $catid ? $pfixtable.".catid = '$catid'" : '';
	        $where_status = isset($_GET['status']) ? "status='{$_GET['status']}'" : '';
	        $status = isset($_GET['status']) && $_GET['status'] == 0 ? 0 :1;
	        $count = $news->where($where_catid)->where($where_status)->where("recycled=0")->count();
	        $page = new page($count, $art_num);
	        $news = $news->field("id,title,click,".$ptable.".status,".$ptable.".catid,cname,addtime,username,mid")->
	                        where($where_catid)->where($where_status)->where("recycled=0")->limit($page->limit())->all();
	        $this->assign("news", $news);
	        $this->assign("page", $page->show(2));
	        $this->assign("status", $status);
	        //栏目操作
	        $cat = M("category");
	        $category = $cat->field("catid,cname,sort,pid,mid")->where(" mid = '".$mid."'")->all();
	        $category = arr::channel($category,"catid","pid",0,0,2,"&nbsp;");
	        $this->assign("category",$category);
	        //文章属性操作
	        $attr = M('attr');
	        $attrs = $attr->field('aid,aname')->all();
	        $this->assign('attrs', $attrs);
	        $this->display();
		}
		/**
		 * 增加文章显示页面
		 */
		public function add_news_show(){
		$catid = isset($_GET['catid']) ? $_GET['catid'] : false;//栏目id
			if($catid === false){
				$this->error('参数错误(查看栏目下文章需要栏目id)','',3);
			}
			$mid = isset($_GET['mid']) ? $_GET['mid'] : false; //模型id
			if($mid === false){
				$this->error('参数错误(查看栏目下文章需要模型id)','',3);
			}
			//遍历得出栏目数组
			$catdb = M("category");
			$category = $catdb->field("catid,cname,pid")->where(" mid = '".$mid."'")->all();
			$category = arr::channel($category, 'catid', 'pid', 0,0, 2);
			$category = delStrValue($category, 'level', 1);
			$this->assign("category", $category);
			$attr = M('attr');
			$attrArr = $attr->findall();
			$this->assign('attr', $attrArr);
			$this->display();
		}
		/**
		 * 执行增加文章的功能
		 */
		public function add_news(){
			
			$mid = $_POST['mid'];
			$prefix = C('DB_PREFIX');
			$table = $this->getAllTableName($mid);
			$ptable = $table['p'];
			$stable = $table['s'];
			$_POST = $this->arr2StrOnDb($_POST);//将表单中的复选框重组
			$_POST[$stable] = $_POST['bigbody'];
			unset($_POST['bigbody']);
			if(isset($_POST['attrrelation'])){
				foreach($_POST['attrrelation'] as $k=>$v){
					$_POST['attrrelation'][$k]['mid'] = $mid;
				}
			}
			$db = R($ptable);
			$db->join = array(
						$stable=>array(
									'type'=>'has_one',
									'foreign_key'=>'nid',
								),
						'attrrelation' => array(
									'type'=>'has_many',
									'foreign_key'=>'nid',
								),
					);
			$_POST[$stable]['userip'] = ip_get_client();
			$_POST['addtime'] = time();
			$_POST['updatetime'] = time();
			$_POST['thumb']=isset($_POST['thumb'][1][0])?$_POST['thumb'][1][0]:'';
			if ($db->add()) {
				$this->success("文章添加成功!  <a href='".__WEB__."'/admin/category/index'>返回栏目页</a>|<a href='".__WEB__."/admin/news/index/mid/".$mid."'>查看文章列表</a>", '', 3);
			} else {
				$this->error("文章添加失败");
			}
		}
		/**
		 * 将文章放入回收站 或者直接删除(配置项修改)
		 */
		public function news_recycle(){
			$mid = isset($_GET['mid']) ? $_GET['mid'] : false; //模型id
			if($mid === false){
				$this->error('参数错误(查看栏目下文章需要模型id)','',3);
			}
			$tables = $this->getAllTableName($mid); //获得所有的表名（有前缀）（无前缀）
			$ptable = $tables['p']; //主表  无前缀
			$stable = $tables['s'];//付表名   不带前缀
			$news = R($ptable);
			if(isset($_POST['xuanze']) && !isset($_GET['nid'])){
				$arr = $_POST['xuanze'];
			}elseif(!isset($_POST['xuanze']) && isset($_GET['nid'])){
				$arr[] = $_GET['nid'];
			}
			if(C('NEWS_DEL_TRUE') || (isset($_GET['del']) && $_GET['del'])){ //彻底删除文章
				$news->join = array(
						$stable => array(
								"type" => "has_one",
								"foreign_key" => "nid"
						),
						'attrrelation' => array(
								'type'=>'has_many',
								'foreign_key'=>'nid',
								'where'=>' mid = '.$mid,
						),
					);
				
				if($news->where(array('id'=>$arr))->del()){
					$this->success('彻底删除成功');
				}else{
					$this->error('彻底删除失败');
				}
			}else{
				$data = array('recycled'=>1);
				if($news->where(array('id'=>$arr))->update($data)){
					$this->success('文章已经放入回收站');
				}else{
					$this->error('文章放入回收站失败');
				}
			}
		}
		/**
		 * 文章还原
		 */
		public function news_huanyuan(){
			$mid = $_GET['mid'];
			$tables = $this->getAllTableName($mid);
			$ptable = $tables['p']; //无前缀 主表 
			$news = M($ptable);
			if(isset($_POST['xuanze']) && !isset($_GET['nid'])){
				$arr = $_POST['xuanze'];
			}elseif(!isset($_POST['xuanze']) && isset($_GET['nid'])){
				$arr = $_GET['nid'];
			}
			$arr;
			$data = array('recycled'=>0);
			if($news->where(array('id'=>$arr))->update($data)){
				$this->success('还原成功');
			}else{
				$this->error('还原失败');
			}
		}
		/**
		 * 多篇文章转成审核或者未审核
		 */
		public function news_shen_many(){
			$mid = $_GET['mid'];
			$tables = $this->getAllTableName($mid);
			$ptable = $tables['p']; //无前缀 主表
			$news = M($ptable);
			if($_GET['shenhe']){ //文章转为审核
				$data = array('status'=>1);
				if($news->where(array('id'=>$_POST['xuanze']))->update($data)){
					$this->success('修改成功');
				}else{
					$this->error('修改失败');
				}
			}else{//文章转为未审核
				$data = array('status'=>0);
				if($news->where(array('id'=>$_POST['xuanze']))->update($data)){
					$this->success('修改成功');
				}else{
					$this->error('修改失败');
				}
			}
		}
		/**
		 * 对多篇文章进行属性操作
		 */
		public function news_attr_many(){
			$attrrelation = M('attrrelation');
			if(!isset($_POST['attrrelation'])){
				$_POST['attrrelation'] = array();
			}
			$attrrelation->validate = array(
						array('xuanze','nonull','您还没有选择文章哦！回去再选一下吧！',2),
					);
			if(!$attrrelation->validate()){
				$this->error($attrrelation->error);
			}
			$_POST['mid'] = $_GET['mid'];
			foreach ($_POST['xuanze'] as $v){
				$attrrelation->where(" nid = '".$v."'")->where(" mid = '".$_POST['mid']."'")->del();
				$error = 0;
				foreach($_POST['attrrelation'] as $value){
					$data = array('nid'=>$v,'aid'=>$value,'mid'=>$_POST['mid']);
					if(!$attrrelation->add($data)){
						$error = 1;
					}
				}
			}
			if(!$error == 1){
				$this->error('抱歉，修改失败了！');
			}else{
				$this->success('恭喜修改成功');
			}
			
		}
		/**
		 * 批量文章移动  不允许跨模型移动文章
		 */
		public function news_yidong_many(){
			//当前文章所在的模型
			$self_mid = isset($_GET['mid']) && !empty($_GET['mid']) ?$_GET['mid']:false;
			if($self_mid === false){
				$this->error('参数错误');
			}
			//想要移动到的栏目
			$tocatids = isset($_POST['yidong']) && !empty($_POST['yidong']) ?$_POST['yidong']:false; 
			if($tocatids === false){
				$this->error('您没有选择要移动到的栏目');
			}
			$tables = $this->getAllTableName($self_mid);
			$ptable = $tables['p']; //主表名 无前缀
			$news = M($ptable);
			$news->where = array(
					'id'=>$_POST['xuanze'],
			);
			$data = array('catid'=>$_POST['yidong']);
			if($news->update($data)){ //更新失败时
				$this->success('恭喜移动成功');
			}else{
				$this->error('可惜，移动失败，请检查选择的数据！');
			}
		}
		/**
		 * 文章修改
		 */
		public function news_modify(){
			$mid = $_GET['mid'];//模型id
			$nid = $_GET['nid']; //文章id
			$table = $this->getAllTableName($mid);
			$ptable = $table['p'];//主表名 不带前缀
			$stable = $table['s'];//付表名   不带前缀
			//获得文章信息
			$news = V($ptable);
			$news->view = array(
						$stable=>array(
							'join_type'=>'inner',
							'on'=>$ptable.'.id = '.$stable.'.nid',
						),
						'category'=>array(
							'join_type'=>'inner',
							'on'=>$ptable.'.catid = category.catid',
							'field'=>'mid',
						),
					);
			$row = $news->where(" id = '".$nid."'")->find();
			$this->assign('news_info', $row);
			//获得该文章属性
			$attr = M('attrrelation');
			$attrs = $attr->where(" nid = '".$nid."'")->where(" mid = '".$mid."'")->findall();
			$attrs = empty($attrs)?array():$attrs;
			$result_attr = arr2toArr1($attrs, 'aid');
			$this->assign('result_attr', $result_attr);
			//获得栏目
			$catdb = M("category");
			$category = $catdb->field("catid,cname,pid")->all();
			$category = arr::channel($category, 'catid', 'pid', 0, 2);
			$this->assign("category", $category);
			//获得所有文章属性
			$attr = M('attr');
			$attrArr = $attr->findall();
			$this->assign('attrs', $attrArr);
			$this->display();
		}
		/**
		 * 执行文章修改
		 */
		public function news_modify_exe(){
			$mid = $_POST['mid'];
			$tables = $this->getAllTableName($mid);
			$ptable = $tables['p']; //主表无后缀
			$stable = $tables['s'];  //附表无后缀
			
			
			$_POST['updatetime'] = time();
			$attr = M('attrrelation');
			//删除文章属性表中的有关这个文章信息。
			$attr->where(" mid = '".$mid."'")->where(" nid = '".$_POST['nid']."'")->del();
			
			$_POST = $this->arr2StrOnDb($_POST);//将表单中的复选框重组
			
			$_POST[$stable] = $_POST['bigbody']; //将表单中的字段转成数据库名
			unset($_POST['bigbody']);
			$model = R($ptable);
			$model->join = array(
					$stable => array(
						"type" => "has_one",
						"foreign_key" => "nid"
					),
				);
			if ($model->where(" id = '".$_POST['nid']."'")->update($_POST)) {
				if(!isset($_POST['attrrelation']) || empty($_POST['attrrelation'])){
					$_POST['attrrelation'] = array();
				}
				foreach ($_POST['attrrelation'] as $k=>$v){
					foreach($v as $key=>$value){
						$attr->add(array('nid'=>$_POST['nid'],'aid'=>$value,'mid'=>$mid));
					}
					
				}
				$this->success("文章修改成功!  <a href='".__WEB__."'/admin/category/index'>返回栏目页</a>|<a href='".__WEB__."/admin/news/index'>查看文章列表</a>", __WEB__."/admin/news/index/catid/".$_POST['catid'].'/mid/'.$mid, 3);
			} else {
				$this->error("文章修改失败");
			}
			
		}
		/**
		 * 显示某个模型下的所有文章
		 */
		public function model_news(){
			$mid = $_GET['mid'];//模型id
			$cat = M('model');
			$model_info = $cat->table('model')->find($mid);
			$ptable = $model_info['ptable']; //获得表名 true 无前缀
			$prefix = c('DB_PREFIX'); //表前缀
			if(isset($_GET['status']) && $_GET['status'] == 100){
				$where_status =  ''; //状态(是否审核)
			}else{
				$where_status = isset($_GET['status']) ? $prefix.$ptable.".status='{$_GET['status']}'" : ''; //状态(是否审核)
			}
			$where_recycled = isset($_GET['recycled']) ? "recycled = '".$_GET['recycled']."'":''; //是否是放入回收站的文章
			$status = isset($_GET['status']) && $_GET['status'] == 0 ? 0 :1; //文章状态
			
			
			$model_news = V($ptable);
			$model_news->view = array(
						'category'=>array(
									'type'=>'inner',
									'field'=>'cname,mid',
									'on'=>'category.catid = '.$ptable.'.catid',
								),
						'user'=>array(
									'type'=>'inner',
									'field'=>'username',
									'on'=>'user.uid = '.$ptable.'.uid',
								),
					);
			$count = $model_news->count();
			$art_num = C('ART_NUM');
			$page = new page($count,$art_num);
			$limit = $page->limit();
			$row = $model_news->where($where_status)->where($where_recycled)->limit($limit)->all();
			//栏目操作
			$cat = M("category");
			$category = $cat->field("catid,cname,sort,pid,mid")->where(" mid = '".$mid."'")->all();
			$category = arr::channel($category,"catid","pid",0,2,"&nbsp;");
			$this->assign("category",$category);
			//文章属性
			$attr = M('attr');
	        $attrs = $attr->field('aid,aname')->all();
	        $this->assign('attrs', $attrs); //发送文章属性
	        $this->assign('model_info', $model_info);
			$this->assign('news', $row);
			$this->assign('page', $page->show(2));
			$this->display();
		}
		
		/**
		 * 获得主副表名
		 * @param number $mid  //模型id
		 * @return Array  //主副表数组 
		 *  0为主表   1为附表
		 */
		public function getAllTableName($mid){
			$prefix = C('DB_PREFIX');//表前缀
			$model = M('model');
			$model_row = $model->find($mid);
			$table['p'] = $model_row['ptable'];//(主表) 无前缀
			$table['s'] = isset($model_row['stable'])?$model_row['stable']:'';//(附表) 无前缀
			$table['pfix'] = $prefix.$table['p'];//(主表) 有前缀
			$table['sfix'] = $prefix.$table['s']; //(附表) 有前缀
			return $table;
		}
		/**
		 * 在文章增加的过程中，可能有复选框（只有复选框能够产生数组），将其重新组合成为字符串，按 , 连接  
		 * 最多支持3级
		 * @param Array $arr
		 * @return string
		 */
		public function arr2StrOnDb($arr){
			$ce = array();
			$ce1= array();
			$ce2 = array();
			foreach($arr as $k=>$v){
				if(is_array($v) && $k != 'bigbody' && $k != 'attrrelation'){
					foreach($v as $key=>$value){
						if(is_array($value)){
							foreach($value as $n=>$m){
								 $ce2[] = $value[$n];
							}
							$arr[$k] = implode(',', $ce2);
						}else{
							if(!empty($value)){
								$ce[] = $v[$key];
							}
							$arr[$k] = implode(',', $ce);
						}
					}
				}elseif(is_array($v) && $k == 'bigbody'){
					foreach($v as $key=>$value){
						if(is_array($value)){
							foreach($value as $n=>$m){
								if(!empty($m)){
									$ce1[] = $value[$n];
								}
							}
							$arr[$k][$key] = implode(',',$ce1);
						}
					}
				}
			}
			return $arr;
		}
	}
?>